package com.mason.forum.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mason.forum.common.APPResult;
import com.mason.forum.common.ResultCode;
import com.mason.forum.utils.SessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-08-24
 * Time: 9:58
 */
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    private ObjectMapper objectMapper;
    @Value("${forum.login.url}")
    private String redirect;//跳转页面

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //业务逻辑
        if (SessionUtils.getUser(request) != null) {
            return true;//用户登录
        }
        log.warn(ResultCode.FAILED_FORBIDDEN.toString() + " 已拦截：" + request.getRequestURI());
        response.setContentType("application/json; charset=utf8");
        //判断路径是否正确
        if (!redirect.startsWith("/")) {
            redirect = "/" + redirect;
        }
        response.getWriter().write(objectMapper.writeValueAsString(APPResult.redirect(redirect)));
//        response.sendRedirect(redirect);
        return false;
    }
}
